/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ChatCliente.java
 *
 * Created on 16/06/2011, 01:31:47
 */
package gui.cliente;


import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Set;

import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;

import negocio.beans.Conversa;
import negocio.beans.Mensagem;
import negocio.beans.Usuario;
import negocio.cliente.FachadaCliente;

/**
 * 
 * @author Eduardo
 */
public class ChatCliente extends javax.swing.JFrame {

	Conversa conversa;
	FachadaCliente fachada;
	AtualizadorMensagens atualizadorMensagem;
	AtualizadorDaLista atualizadorDaLista;

	/** Creates new form ChatCliente */
	public ChatCliente(Usuario amigo) {
		initComponents();
		fachada = FachadaCliente.getInstance();
		conversa = fachada.iniciarConversa(amigo, null);
		atualizadorMensagem = new AtualizadorMensagens();
		atualizadorMensagem.start();
		atualizadorDaLista = new AtualizadorDaLista();
		atualizadorDaLista.start();
		this.jTextArea2.grabFocus();
	}

	public ChatCliente(Conversa conversa) {
		initComponents();
		this.setVisible(false);
		fachada = FachadaCliente.getInstance();
		this.conversa = conversa;
		atualizadorMensagem = new AtualizadorMensagens();
		atualizadorMensagem.start();
		atualizadorDaLista = new AtualizadorDaLista();
		atualizadorDaLista.start();
		this.jTextArea2.grabFocus();
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jPanel1 = new BackgroundPanel4();
		jLabel1 = new javax.swing.JLabel();
		jScrollPane3 = new javax.swing.JScrollPane();
		jList1 = new javax.swing.JList();
		jPanel2 = new BackgroundPanel3();
		jScrollPane1 = new javax.swing.JScrollPane();
		jTextArea1 = new javax.swing.JTextArea();
		jPanel3 = new BackgroundPanel3();
		jScrollPane2 = new javax.swing.JScrollPane();
		jTextArea2 = new javax.swing.JTextArea();
		jButton1 = new javax.swing.JButton();
		jMenuBar1 = new javax.swing.JMenuBar();
		jMenu1 = new javax.swing.JMenu();
		jMenuItem3 = new javax.swing.JMenuItem();
		jMenu2 = new javax.swing.JMenu();
		jMenuItem4 = new javax.swing.JMenuItem();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("[SKY-PE]");
		setForeground(java.awt.Color.white);

		jLabel1.setFont(new java.awt.Font("SansSerif", 1, 14));
		jLabel1.setText("Conversando com:");

		unsortedModel = new DefaultListModel();
		sortedModel = new SortedListModel(unsortedModel);

		jList1.setModel(sortedModel);

		jScrollPane3.setViewportView(jList1);

		jTextArea1.setColumns(20);
		jTextArea1.setEditable(false);
		jTextArea1.setRows(5);
		jScrollPane1.setViewportView(jTextArea1);

		javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
		jPanel2.setLayout(jPanel2Layout);
		jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel2Layout.createSequentialGroup().addGap(19, 19, 19).addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 901, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addContainerGap(19, Short.MAX_VALUE)));
		jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel2Layout.createSequentialGroup().addContainerGap().addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE).addContainerGap()));

		jTextArea2.setColumns(20);
		jTextArea2.setRows(5);
		jTextArea2.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				jTextArea2KeyPressed(evt);
			}
		});
		jScrollPane2.setViewportView(jTextArea2);

		jButton1.setText("Enviar");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});
		jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				jButton1KeyPressed(evt);
			}
		});

		javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
		jPanel3.setLayout(jPanel3Layout);
		jPanel3Layout.setHorizontalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel3Layout
						.createSequentialGroup()
						.addGap(18, 18, 18)
						.addGroup(
								jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
										.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 902, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap(19, Short.MAX_VALUE)));
		jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel3Layout.createSequentialGroup().addContainerGap().addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(jButton1).addContainerGap(22, Short.MAX_VALUE)));

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout
				.setHorizontalGroup(jPanel1Layout
						.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
						.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												jPanel1Layout
														.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																jPanel1Layout.createSequentialGroup().addGap(10, 10, 10)
																		.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 898, javax.swing.GroupLayout.PREFERRED_SIZE))
														.addComponent(jLabel1)).addGap(21, 21, 21)));
		jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel1Layout.createSequentialGroup().addComponent(jLabel1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)));

		jMenu1.setText("Conversa");

		jMenuItem3.setText("Sair da Conversa");
		jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenuItem3ActionPerformed(evt);
			}
		});
		jMenu1.add(jMenuItem3);

		jMenuBar1.add(jMenu1);

		jMenu2.setText("Amigos");

		jMenuItem4.setText("Convidar Amigo");
		jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenuItem4ActionPerformed(evt);
			}
		});
		jMenu2.add(jMenuItem4);

		jMenuBar1.add(jMenu2);

		setJMenuBar(jMenuBar1);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
				javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE));
		layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
				Short.MAX_VALUE));

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton1ActionPerformed
		// TODO add your handling code here:
		String texto = this.jTextArea2.getText();

		escreveNoTextField("Eu falei: " + texto + "\n");

		Mensagem mensagem = new Mensagem(texto);
		conversa.enviarMensagem(mensagem);

		conversa.enviarMensagem(mensagem);
		this.jTextArea2.setText("");
		this.jTextArea2.grabFocus();
	}// GEN-LAST:event_jButton1ActionPerformed

	private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton3ActionPerformed
		// TODO add your handling code here:
		// enviar arquivo
		ProcurandoArquivo arquivo = new ProcurandoArquivo();

		arquivo.setLocationRelativeTo(this);
		arquivo.setVisible(true);
	}// GEN-LAST:event_jButton3ActionPerformed

	private void jButton3KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jButton3KeyPressed
		// TODO add your handling code here:
		if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			// enviar arquivo
			ProcurandoArquivo arquivo = new ProcurandoArquivo();

			arquivo.setLocationRelativeTo(this);
			arquivo.setVisible(true);
		}
	}// GEN-LAST:event_jButton3KeyPressed

	private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton2ActionPerformed
		// TODO add your handling code here:
		// iniciar audio
		Object obj = this.jList1.getSelectedValue();

		System.out.println("Ligação: " + obj.toString());

		PopOutAudio audio = new PopOutAudio();

		audio.setLocationRelativeTo(this);
		audio.setVisible(true);
	}// GEN-LAST:event_jButton2ActionPerformed

	private void jButton2KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jButton2KeyPressed
		// TODO add your handling code here:
		// iniciar audio
		if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			Object obj = this.jList1.getSelectedValue();

			System.out.println("Ligação: " + obj.toString());
			PopOutAudio audio = new PopOutAudio();

			audio.setLocationRelativeTo(this);
			audio.setVisible(true);
		}
	}// GEN-LAST:event_jButton2KeyPressed

	private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jButton1KeyPressed
		// TODO add your handling code here:
		if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			String texto = this.jTextArea2.getText();

			escreveNoTextField("Eu falei: " + texto + "\n");

			Mensagem mensagem = new Mensagem(texto);
			conversa.enviarMensagem(mensagem);

			conversa.enviarMensagem(mensagem);
			this.jTextArea2.setText("");
			evt.consume();
			this.jTextArea2.grabFocus();
		}
	}// GEN-LAST:event_jButton1KeyPressed

	private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jMenuItem1ActionPerformed
		// TODO add your handling code here:
		// iniciar audio
		PopOutAudio audio = new PopOutAudio();

		audio.setLocationRelativeTo(this);
		audio.setVisible(true);
	}// GEN-LAST:event_jMenuItem1ActionPerformed

	private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jMenuItem3ActionPerformed
		// TODO add your handling code here:
		this.dispose();
	}// GEN-LAST:event_jMenuItem3ActionPerformed

	private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jMenuItem4ActionPerformed
		// TODO add your handling code here:
		// convidar amigo
		ConvidarAmigo convite = new ConvidarAmigo(this.conversa);

		convite.setLocationRelativeTo(this);
		convite.setVisible(true);
	}// GEN-LAST:event_jMenuItem4ActionPerformed


	
	private void jTextArea2KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jTextArea2KeyPressed
		// TODO add your handling code here:
		if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
			String texto = this.jTextArea2.getText();

			escreveNoTextField("Eu falei: " + texto + "\n");

			Mensagem mensagem = new Mensagem(texto);
			conversa.enviarMensagem(mensagem);

			this.jTextArea2.setText("");

			evt.consume();
		}
	}// GEN-LAST:event_jTextArea2KeyPressed

	private void escreveNoTextField(String string) {
		if (!this.isVisible()) {
			this.setVisible(true);
		}
		this.jTextArea1.append(string);
	}

	/**
	 * @param args
	 *            the command line arguments
	 */

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton jButton1;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JList jList1;
	private javax.swing.JMenu jMenu1;
	private javax.swing.JMenu jMenu2;
	private javax.swing.JMenuBar jMenuBar1;
	private javax.swing.JMenuItem jMenuItem3;
	private javax.swing.JMenuItem jMenuItem4;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JPanel jPanel2;
	private javax.swing.JPanel jPanel3;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JScrollPane jScrollPane3;
	private javax.swing.JTextArea jTextArea1;
	private javax.swing.JTextArea jTextArea2;

	// End of variables declaration//GEN-END:variables

	private SortedListModel sortedModel;
	private DefaultListModel unsortedModel;

	private class AtualizadorDaLista implements Runnable {

		private boolean running;

		public AtualizadorDaLista() {
			running = true;
		}

		public void start() {
			Thread th = (new Thread(this));
			th.setPriority(Thread.MIN_PRIORITY);
			th.start();
		}

		public void stop() {
			running = false;
		}

		@Override
		public void run() {
			while (running) {

				try {
					SwingUtilities.invokeLater(new Runnable() {

						@Override
						public void run() {

							Set<Usuario> novaLista = conversa.getPessoas().keySet();
							// System.out.println(novaLista);
							for (Object amigo : unsortedModel.toArray()) {
								if (!novaLista.contains((Usuario) amigo)) {
									// System.out.println("Removendo Usuario");
									unsortedModel.removeElement(amigo);
								}
							}

							for (Usuario amigo : novaLista) {
								int indice = unsortedModel.indexOf(amigo);
								if (indice != -1) {
									unsortedModel.set(indice, amigo);
									// System.out.println("Atualizando usuario");
								} else {
									// System.out.println("Adicionando usuario");
									unsortedModel.addElement(amigo);
								}
							}
						}
					});

					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	private class AtualizadorMensagens implements Runnable {

		private boolean running;

		private class Escritor implements Runnable {
			Mensagem mensagem;

			public Escritor(Mensagem mensagem) {
				this.mensagem = mensagem;
			}

			@Override
			public void run() {
				escreveNoTextField(mensagem.toString());
			}
		}

		public AtualizadorMensagens() {
			running = true;
		}

		public void start() {
			Thread th = (new Thread(this));
			th.setPriority(Thread.MIN_PRIORITY);
			th.start();
		}

		public void stop() {
			running = false;
		}

		@Override
		public void run() {
			while (running) {

				try {
					Mensagem mensagem = conversa.receberMensagem();

					SwingUtilities.invokeLater(new Escritor(mensagem));

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
